// pages/list/index.js
import {
  getListData,
  likeOrCancelLikeRequest,
  deleteRequest,
} from "../../utils/dataBase";
import eventBus from "../../utils/eventBus";
Page({
  data: {
    listData: [],
  },
  onLoad(options) {
    this.getListDataAndRender();
    this.listenEventTrigger();
  },
  onUnload() {
    this.cancelEventTrigger();
  },
  listenEventTrigger() {
    this.detailLikeOrCancelLikeEventId = eventBus.on(
      "detailLikeOrCancelLike",
      (deliverData) => {
        const { id, result } = deliverData;
        this.afterLikeOrCancelLikeReRenderItem(id, result);
      }
    );
    this.detailDeleteEventId = eventBus.on("detailDelete", (deliverData) => {
      const { id, result } = deliverData;
      this.afterDeleteListItemReRender(id, result);
    });
  },
  cancelEventTrigger() {
    eventBus.remove(
      "detailLikeOrCancelLike",
      this.detailLikeOrCancelLikeEventId
    );
  },
  getListDataAndRender() {
    const result = getListData();
    result.forEach((item) => {
      item.show = true;
      item.style = {
        height: "auto",
      };
    });
    this.setData({
      listData: [...this.data.listData, ...result],
    });
    console.log(this.data.listData);
  },
  goToDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `../detail/index?id=${id}`,
    });
  },
  likeOrCancelLike(e) {
    const { id } = e.currentTarget.dataset;
    const result = likeOrCancelLikeRequest(+id);
    this.afterLikeOrCancelLikeReRenderItem(id, result);
  },
  async deleteListItem(e) {
    const sureResult = await wx.showModal({
      title: "提示",
      content: "确定要删除这项吗",
    });
    if (sureResult.confirm) {
      wx.showToast({
        icon: "loading",
        duration: 10000,
      });
      const { id } = e.currentTarget.dataset;
      const result = await deleteRequest(+id);
      if (result) {
        wx.hideToast();
        this.afterDeleteListItemReRender(+id, result);
      }
    }
  },
  /**
   * 获取并设置设置list每一项的dom元素的高度
   */
  async setDomHeight(index) {
    await new Promise((resolve) => {
      const query = wx.createSelectorQuery().in(this);
      query
        .select(`#list-item-${index}`)
        .boundingClientRect((data) => {
          this.setData({
            [`listData[${index}].style`]: { height: `${data.height}px` },
          });
          console.log(index, data.height);
          resolve(data);
        })
        .exec();
    });
  },
  /**
   * 点赞或取消点赞后重新渲染列表中对应id项的视图
   * 通过id找到对应的索引i
   * @param {*} id 通过id找到对应的索引i
   */
  afterLikeOrCancelLikeReRenderItem(id, result) {
    const { isLiked, likeNums, status } = result;
    if (status === 1) {
      const { listData } = this.data;
      for (let i = 0; i < listData.length; i++) {
        const item = listData[i];
        if (item.id === id) {
          this.setData({
            [`listData[${i}].isLiked`]: isLiked,
            [`listData[${i}].likeNums`]: likeNums,
          });
          break;
        }
      }
    }
  },
  /**
   * 删除后重新渲染列表中对应id项的视图
   * 通过id找到对应的索引 index
   * @param {*} id 通过id找到对应的索引 index
   */
  async afterDeleteListItemReRender(id, result) {
    if (result) {
      const { listData } = this.data;
      for (let index = 0; index < listData.length; index++) {
        const item = listData[index];
        if (item.id === id) {
          // 获取点击元素的高度为点击的元素设置高度，这个高度是让transition动画起效果而设置上的
          await this.setDomHeight(index);
          // 等80ms，让data.height赋值到dom元素上后再把高度设置为0，这样才不会没有动画效果的情况
          setTimeout(() => {
            this.setData({
              [`listData[${index}].show`]: false,
              [`listData[${index}].style`]: { height: `0px` },
            });
          }, 80);
          break;
        }
      }
    }
  },
});
